package org.zj.chat;


import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

//封装websocket到TextWebSocketFrame中
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    //用来保存所有的客户端连接
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:MM");


    /**
     * 有新的客户端连接的时候调用
     *
     * @param ctx
     * @throws Exception
     */
    @Override

    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //有新的客户端来的时候加入channelGroup中
        clients.add(ctx.channel());
    }

    /**
     * 当channel中有新的事件消息时调用
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //获取客户端的消息
        //System.out.println("接受到的消息数据为:" + text);
        //将消息发送到所有的客户端
        //System.out.println(clients.size());
        for (Channel client : clients) {
            if(!ctx.channel().equals(client))
                client.writeAndFlush(new TextWebSocketFrame(msg.text()));
        }

    }
}
